<?php
import('ORG.Util.Function');
import('@.Org.BaseTool');
import('@.Org.CommonTool');
import('@.Org.UserTool');
import('@.Org.Message');
import('@.Org.PassTool');

class PassAction extends CommonAction {
		
	protected function _initialize(){
		parent::_initialize();		
	}
	
	public function _empty(){
		$this->redirect("/pass/login");
	}
	
	//测试同步登陆
	public function ceshi(){
		include_once UC_CLIENT_PATH . 'client/' . 'client.php';
		echo '<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">登陆成功';
		
		list($uid, $username, $password, $email) = uc_user_login("15626712840", "123456");
		if($uid > 0) {
			echo '登录成功';
			echo uc_user_synlogin($uid);			
			
		} elseif($uid == -1) {
			echo '用户不存在,或者被删除';
		} elseif($uid == -2) {
			echo '密码错';
		} else {
			echo '未定义';
		}	
	}
	
	public function tuichu(){
		include_once UC_CLIENT_PATH . 'client/' . 'client.php';
		echo uc_user_synlogout();
		echo "登出成功";
	}
	
    public function login(){
    	//titile
		$this->assign("global_title",		"用户登陆_音伴尔官网"); 
    	//禁止缓存
    	forbid_cache();
    	$action				=	empty($_REQUEST['act']) ? 'login' : $_REQUEST['act'];  
    	$back_url			=	empty($_GET['back_url'])? '' : $this->_get('back_url');  

    	//第三方平台
    	Vendor("Api.Sina.config");
		Vendor("Api.Sina.saetv2");	
		$o = new SaeTOAuthV2( WB_AKEY  );
		$code_url = $o->getAuthorizeURL( WB_CALLBACK_URL );						
		$this->assign("code_url",	$code_url);
    	
    	$this->assign("action",				$action);
    	$this->assign("back_url",			$back_url);
    	$this->assign("enabled_captcha",	1); /*显示验证码*/ 
		$this->display('Pass:user_passport');
    }
	
    public function checklogin(){ 
    	import("ORG.Util.RBAC");		// 权限类
    	//UC
    	/*Vendor('Integrates.ucenter');
    	$User				=	new Ucenter();*/
    	//QS
    	Vendor('Integrates.ecshop');
    	$User				=	new Ecshop();
    	    	
    	$GLOBALS['ecs']		=	& $User;    	    	
    	$UserModel			=	M('Users');
    	
		//令牌检验
		if( M()->autoCheckToken($_POST) ){
			$username 		= 	isset($_POST['username']) 	? trim($_POST['username']) : '';
		    $password 		= 	isset($_POST['password']) 	? trim($_POST['password']) : '';
		    $verify_code	= 	md5(isset($_POST['captcha'])? trim($_POST['captcha']) : ''); //md5加密
		    $back_act 		= 	isset($_POST['back_act']) 	? trim($_POST['back_act']) : '';
			
			if($User->login($username, $password,isset($_POST['remember']))){
				update_user_info(); 	//更新用户登陆信息
				recalculate_price();	//重新计算用户的折扣和优惠
				
				//设置用户权限
				$result		=	set_user_auth($username);				
				
				//判断是否存在跳转地址
				if(empty($_REQUEST['back_url'])){
					$this->redirect('/user/info', null, 2, '<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">登陆成功' . uc_call("uc_user_synlogin", array( $_SESSION['uid'] ) ) );	
				}
				else{
					$this->redirect($_POST['back_url'], null, 2, '<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">登陆成功' . uc_call("uc_user_synlogin", array( $_SESSION['uid'] ) ) );
				}
			}
			else{
				$_SESSION['login_fail'] ++ ;
				$this->redirect('/pass/login','',2,'<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">登陆失败');
			}
		}
		else{			
			$this->redirect('/pass/login', '', 2,'<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">请不要点击两次登陆,正在为您跳转...');
		}	
    }
    
    /**
     * 验证码
     * Enter description here ...
     */
	Public function verify(){
	    import('ORG.Util.Image');
	    Image::buildImageVerify();
	}
	
	/**
	 * 退出系统
	 * Enter description here ...
	 */
	public function logout(){
		//titile
		$this->assign("global_title",		"用户登出_音伴尔官网"); 
		//uc插件
		include_once UC_CLIENT_PATH . 'client/' . 'client.php';
		//$User				=	new Ecshop();
		Vendor('Integrates.ucenter');		
    	$User				=	new Ucenter();	
    	$GLOBALS['ecs']		=	& $User;
	    $User->logout();

	    $ucdata 			=	empty($User->ucdata)? "" : $User->ucdata;
		/* thinkPHP--登陆处理  */
	    if(isset($_SESSION[C('USER_AUTH_KEY')])){
			unset($_SESSION[C('USER_AUTH_KEY')]);
			unset($_SESSION);
			session_destroy();	
        }else {
        	unset($_SESSION);
        	session_destroy();
        }   
        $msg				=	build_tips_msg(QS_GENERAL_TIPS);
        $msg['tips_text']	=	"退出系统成功,购物车为空,到处逛逛咯^_^" . uc_user_synlogout();;     
        $this->assign("msg",			$msg);
        $this->assign("show_tips_img",	1);
        $this->display('msg');
	}
	
	/**
	 * 注册页面
	 * Enter description here ...
	 */
	public function register(){
		//titile
		$this->assign("global_title",		"用户注册_音伴尔官网"); 
		$this->assign("action",'register');
		$this->display('user_passport');
	}
	
	/**
	 * 处理注册
	 * Enter description here ...
	 */
	public function register_ok(){		
		$CommonModel			=	new CommonModel();
		$username 				= 	isset($_POST['username']) ? trim($_POST['username']) : '';
        $password 				= 	isset($_POST['password']) ? trim($_POST['password']) : '';
        $captcha 				= 	isset($_POST['captcha']) ? md5( trim($_POST['captcha']) ) : '';
        $email					=	isset($_POST['email']) ? trim($_POST['email']):'';
        $mobile					=	isset($_POST['mobile']) ? trim($_POST['mobile']) : '';	
        $mobileCode				=	isset($_POST['mobileValidateCode']) ? md5( trim($_POST['mobileValidateCode']) ) : '';
        $register_type			=	'';        
        $register_field			=	'';
                
    	//过滤不符合条件
        if( md5($_SESSION['code']) != $mobileCode ){
      	 	$this->error('验证码不匹配');
        }          
        if(empty($_POST['agreement'])){
            $this->error("不同意用户协议,不能注册");
        }
        if (strlen($password) < 6){
            $this->error($GLOBALS['_LANG']['passport_js']['password_shorter']);
        }
        if (strpos($password, ' ') > 0){
            $this->error($GLOBALS['_LANG']['passwd_balnk']);
        }
		
		$username		=	trim($_POST['mobile']);
		$password		=	trim($_POST['password']);
		$register_field	=	trim($_POST['mobile']) . '@qq.com';
		
        if ( false != register($username, $password, $register_field, $other) ){
            //把新注册用户的扩展信息插入数据库
        	//1:读出所有自定义扩展字段的id
            $sql 				= 	'SELECT id FROM ' . 'reg_reg_fields' . ' WHERE type = 0 AND display = 1 ORDER BY dis_order, id';   
            $fields_arr 		= 	M()->query($sql);
			
            //2:生成扩展字段的内容字符串
            $extend_field_str 	= 	'';    
            foreach ($fields_arr AS $val){
                $extend_field_index = 'extend_field' . $val['id'];
                if(!empty($_POST[$extend_field_index])){
                    $temp_field_content = 	strlen($_POST[$extend_field_index]) > 100 ? mb_substr($_POST[$extend_field_index], 0, 99) : $_POST[$extend_field_index];
                    $extend_field_str 	.= 	" ('" . $_SESSION['user_id'] . "', '" . $val['id'] . "', '" . compile_str($temp_field_content) . "'),";
                }
            }            
            $extend_field_str 	= 	substr($extend_field_str, 0, -1);
            
           	//3:插入注册扩展数据           	
            if ($extend_field_str){
                $sql 			= 	'INSERT INTO '. ' ybr_reg_extend_info ' . ' (`user_id`, `reg_field_id`, `content`) VALUES' . $extend_field_str;
                M()->query($sql);
            }
            
            //4:写入密码提示问题和答案 
            if (!empty($passwd_answer) && !empty($sel_question)){
                $sql 			= 	'UPDATE ' . 'ybr_users' . " SET `passwd_question`='$sel_question', `passwd_answer`='$passwd_answer'  WHERE `user_id`='" . $_SESSION['user_id'] . "'";
                M()->query($sql);
            }
            
            //5:同步UC用户的JS代码
            $ucdata 			= 	empty($user->ucdata)? "" : $user->ucdata;
            
            $msg				=	build_tips_msg(QS_GENERAL_TIPS);   
            $msg['tips_text']	=	"用户&nbsp;&nbsp;" . $username . "&nbsp;&nbsp;注册成功,去逛逛呗^_^亲";   
            $msg['is_auto_jump']= 	1;
			$msg['jump_content']= 	'<meta http-equiv="Refresh" content="3;url=' . U('user/info') . '" />';
			$this->assign('msg',			$msg);
			$this->assign("show_tips_img",	1);
            $this->display("msg");      
        }
        else{
            $msg					=	build_tips_msg($msg_type);
        	$msg['tips_text']		=	$GLOBALS['error'];
            $msg['is_auto_jump'] 	= 	1;
			$msg['jump_content'] 	= 	'<meta http-equiv="Refresh" content="3;url=' . U('pass/register') . '" />';
            $this->assign('msg',$msg);
            $this->display('msg');        
        }           
	}
	
	/**
	 * 发送手机注册验证码
	 * Enter description here ...
	 */
	public function send_mobile_code(){		
		$mobile		=	trim($_REQUEST['mobile']);
				
		//手机号码为是否为空
		if(empty($mobile)){
			$this->ajaxReturn(0,"手机号码不能为空",1);
		}
		//判断手机号码长度是否正确
		if(strlen($mobile) != 11){
			$this->ajaxReturn(0,"手机号码长度不对",1);
		}
		//判断是否为手机号码格式
		$m_reg						=	'/^13[0-9]{1}[0-9]{8}$|14[0-9]{9}$|15[01689]{1}[0-9]{8}$|189[0-9]{8}$|171[0-9]{8}$|18[0-9]{9}/';
	    preg_match_all($m_reg, $mobile, $m);	    
	    if(empty($m[0])){
	    	$this->ajaxReturn(0,"手机号码格式不正确",1);
	    }
		//判断是否已经注册
	    if(is_user_exists($mobile)){
	    	$this->ajaxReturn(0,"该用户已被注册",1);
	    }
	    
	    //系统随机生成手机验证码
	    $code		=	createVerifyCode(4);
		$reg		=	Message::sendCode($mobile, $code);
		if($reg){
			$this->ajaxReturn(1,"验证码发送成功",1);
		}
		else{
			$this->ajaxReturn(0,"验证发送失败,请点击重新发送",1);
		}
	}
	
	/**
	 * 获取密码
	 * Enter description here ...
	 */
	public function get_password(){
		//titile
		$this->assign("global_title",		"找回密码_音伴尔官网");
		$this->display();
	}
	
	public function set_password(){
		$mobile		=	trim($_REQUEST['mobile']);
		$code		=	md5(trim($_REQUEST['code']));
		$password	=	trim($_REQUEST['password']);
	
		//帅选
		if(empty($mobile)){
			$this->ajaxReturn("手机不能为空","error",1);
		}
		if(empty($code)){
			$this->ajaxReturn("验证码不能为空","error",1);
		}
		if(empty($password)){
			$this->ajaxReturn("密码不能为空","error",1);
		}
		
		//UC
		/*Vendor('Integrates.ucenter');    	
    	$User				=	new Ucenter();*/
		//QS
		Vendor('Integrates.ecshop');
		$User				=	new Ecshop();
		
		$GLOBALS['ecs']		=	& $User;
		$UserModel			=	M('Users');
		
    	/*uc用户数据
    	$datas				=	$GLOBALS['ecs']->get_profile_by_name($mobile);
    	if(!empty($datas)){
    		list($uid, $username, $email) = $datas;
			//修改密码
    		//$GLOBALS['ecs']->
    	}
    	*/
		
    	//QS用户数据		
		$user_datas		=	M('Users')->field("user_id,user_name")->where("user_name = '{$mobile}'")->find();
		
		if(empty($user_datas)){
			$this->ajaxReturn("该手机号码不存在","error",1);
		}
		if($code != md5($_SESSION['code'])){
			$this->ajaxReturn("验证码不正确","error",1);
		}		
		if($code == md5($_SESSION['code'])){
			$cfg['password']	=	$password;
			$cfg['md5password']	=	'';			
			$cfg['username']	=	$mobile;
			//清楚加密数字串
			M("Users")->where("user_name='{$mobile}'")->setField("ec_salt",NULL);
			//修改密码
			$result				=	$GLOBALS['ecs']->edit_user($cfg);
			
			if($result){
				$this->ajaxReturn("密码重置成功","ok",1);
			}
			else{
				$this->ajaxReturn("重置失败","error",1);
			}
		}		
		else{
			$this->ajaxReturn("该用户号码不存在","error",1);
		}
	}
	
	/**
	 * 发送验证码
	 * Enter description here ...
	 */
	public function send_verify_code(){
		import("@.Org.Message");
		$mobile	=	trim($_REQUEST['mobile']);
		//判断号码是否存在		
		$code		=	createVerifyCode(4);
		$reg		=	Message::sendCode($mobile, $code);
		if($reg){
			$this->ajaxReturn(1,"ok",1);
		}
		else{
			$this->ajaxReturn(1,"error",1);
		}
	}
	
	public function check_code(){
		$code	=	md5(trim($_REQUEST['code']));
		if($code = $_SESSION['code']){
			$this->ajaxReturn(1,"ok",1);
		}
		else{
			$this->ajaxReturn(1,"error",1);
		}		
	}
	
	//测试
	public function weibo(){				
		
		$this->display();
	}
	
	//微博登陆毁掉掉函数
	public function weibo_callback(){		
		Vendor("Api.Sina.config");
		Vendor("Api.Sina.saetv2");	
		
		$o = new SaeTOAuthV2( WB_AKEY , WB_SKEY );
		
		if (isset($_REQUEST['code'])) {
			$keys = array();
			$keys['code'] = $_REQUEST['code'];
			$keys['redirect_uri'] = WB_CALLBACK_URL;
			try {
				$token = $o->getAccessToken( 'code', $keys ) ;
			} catch (OAuthException $e) {
			}
		}
		
		if ($token) {
			$_SESSION['token'] = $token;
			setcookie( 'weibojs_'.$o->client_id, http_build_query($token) );
		}
					
		$c 		= 	new SaeTClientV2( WB_AKEY , WB_SKEY , $_SESSION['token']['access_token'] );
		$ms  	= 	$c->home_timeline();
		$uid_get= 	$c->get_uid();
		$uid 	= 	$uid_get['uid'];
		//根据ID获取用户等基本信息
		$user_message 	= 	$c->show_user_by_id( $uid);
		
		$user_info['id']		=	$user_message['id'];
		$user_info['idstr']		=	$user_message['idstr'];
		$user_info['name']		=	$user_message['name'];
		$user_info['province']	=	$user_message['province'];
		$user_info['city']		=	$user_message['city'];
		$user_info['profile_image_url']		=	$user_message['profile_image_url'];

		$this->assign("global_title",	"新浪微博登陆_音伴尔官网");
		$this->assign("user_message", 	$user_message);
		$this->assign("type", 			"weibo");
		$this->display('complete_telinput');
	}
	
	/**
	 * 设置API方式等l
	 * Enter description here ...
	 */
	public function set_api_register(){
		//取参数
		$username		=	trim($_POST["mobile"]);
		$password		=	trim($_POST["password"]);
		$register_field	=	trim($_POST['mobile']) . '@qq.com';
				
        if ( false != register($username, $password, $register_field, $other) ){
            //把新注册用户的扩展信息插入数据库
        	//1:读出所有自定义扩展字段的id
            $sql 				= 	'SELECT id FROM ' . 'reg_reg_fields' . ' WHERE type = 0 AND display = 1 ORDER BY dis_order, id';   
            $fields_arr 		= 	M()->query($sql);
			
            //2:生成扩展字段的内容字符串
            $extend_field_str 	= 	'';    
            foreach ($fields_arr AS $val){
                $extend_field_index = 'extend_field' . $val['id'];
                if(!empty($_POST[$extend_field_index])){
                    $temp_field_content = 	strlen($_POST[$extend_field_index]) > 100 ? mb_substr($_POST[$extend_field_index], 0, 99) : $_POST[$extend_field_index];
                    $extend_field_str 	.= 	" ('" . $_SESSION['user_id'] . "', '" . $val['id'] . "', '" . compile_str($temp_field_content) . "'),";
                }
            }            
            $extend_field_str 	= 	substr($extend_field_str, 0, -1);
            
           	//3:插入注册扩展数据           	
            if ($extend_field_str){
                $sql 			= 	'INSERT INTO '. ' ybr_reg_extend_info ' . ' (`user_id`, `reg_field_id`, `content`) VALUES' . $extend_field_str;
                M()->query($sql);
            }
            
            //4:写入密码提示问题和答案 
            if (!empty($passwd_answer) && !empty($sel_question)){
                $sql 			= 	'UPDATE ' . 'ybr_users' . " SET `passwd_question`='$sel_question', `passwd_answer`='$passwd_answer'  WHERE `user_id`='" . $_SESSION['user_id'] . "'";
                M()->query($sql);
            }
            
            //5:同步UC用户的JS代码
            $ucdata 			= 	empty($user->ucdata)? "" : $user->ucdata;
            
            $msg				=	build_tips_msg(QS_GENERAL_TIPS);   
            $msg['tips_text']	=	"用户&nbsp;&nbsp;" . $username . "&nbsp;&nbsp;注册成功,去逛逛呗^_^亲";   
            $msg['is_auto_jump']= 	1;
			$msg['jump_content']= 	'<meta http-equiv="Refresh" content="3;url=' . U('user/info') . '" />';
			$this->assign('msg',			$msg);
			$this->assign("show_tips_img",	1);
            $this->display("msg");      
        }
        else{
            $msg					=	build_tips_msg($msg_type);
        	$msg['tips_text']		=	$GLOBALS['error'];
            $msg['is_auto_jump'] 	= 	1;
			$msg['jump_content'] 	= 	'<meta http-equiv="Refresh" content="3;url=' . U('pass/register') . '" />';
            $this->assign('msg',$msg);
            $this->display('msg');        
        }           
	}	
	
	public function register_later(){
				
		$type	=	empty($_REQUEST['type']) ? 'sina' : $_REQUEST['type'];
		
		if($type == 'weibo'){
			Vendor("Api.Sina.config");
			Vendor("Api.Sina.saetv2");	
			$c 		= 	new SaeTClientV2( WB_AKEY , WB_SKEY , $_SESSION['token']['access_token'] );
			$ms  	= 	$c->home_timeline();
			$uid_get= 	$c->get_uid();
			$uid 	= 	$uid_get['uid'];
			//根据ID获取用户等基本信息
			$user_message 	= 	$c->show_user_by_id( $uid);
			//设置session
			$_SESSION[C('USER_AUTH_KEY')]	=	$user_message['id'];
			$_SESSION['name']         		=  	$user_message['name'];
			$_SESSION['user_name']    		=   $user_message['name'];	//兼容前台用户
			$_SESSION['id']          	 	=   $user_message['id'];
			$_SESSION['user_id']      		=   $user_message['id'];	//兼容前台用户系统				
		}
		else if($type == 'qq'){
			vendor("Api.QQ.qqConnectAPI");
			$qc 			= 	new QC();
			$qc 			= 	new QC($_SESSION['QQ_TOKEN']['access'],$_SESSION['QQ_TOKEN']['openid']);
			$user_message 	= 	$qc->get_user_info();
			//QQ不返回uid
			$user_message['id']	=	rand(9999, 10000);
			
			$_SESSION['QQ_TOKEN']['access']	=	$acs;
			$_SESSION['QQ_TOKEN']['openid']	=	$oid;
			//设置session
			$_SESSION[C('USER_AUTH_KEY')]	=	$user_message['id'];
			$_SESSION['name']         		=  	$user_message['nickname'];
			$_SESSION['user_name']    		=   $user_message['nickname'];	//兼容前台用户
			$_SESSION['id']          	 	=   $user_message['id'];
			$_SESSION['user_id']      		=   $user_message['id'];	//兼容前台用户系统			
		}
		//跳转到用户页面
		$this->redirect("/user/info");
	}	
	
	public function qq_login(){		
		vendor("Api.QQ.qqConnectAPI");
		$qc = new QC();
		$qc->qq_login();
	}
	
	public function qq_callback(){
		vendor("Api.QQ.qqConnectAPI");
		$qc 			= 	new QC();
		$acs 			= 	$qc->qq_callback();
		$oid 			= 	$qc->get_openid();
		$qc 			= 	new QC($acs,$oid);
		$user_message 	= 	$qc->get_user_info();		
		
		$_SESSION['QQ_TOKEN']['access']	=	$acs;
		$_SESSION['QQ_TOKEN']['openid']	=	$oid;
		
		$user_info['id']		=	$user_message['id'];
		$user_info['name']		=	$user_message['nickname'];
		$user_info['province']	=	$user_message['province'];
		$user_info['city']		=	$user_message['city'];
		$user_info['profile_image_url']		=	$user_message['figureurl_1'];		
		$_SESSION['qqapi']['code']	=	$_REQUEST['code'];
		
		$this->assign("global_title",	"QQ用户登陆_音伴尔官网"); 
		$this->assign("user_message", 	$user_info);
		$this->assign("type", 			"qq");
		$this->assign("code", 			$_REQUEST['code']);
		$this->display('complete_telinput');
	}	
		
	//快递查询
	public function kuaidi100(){		
				
		$this->display();
	}
	
	
	public function express_query(){
		$com		=	$_REQUEST['com'];
		$num		=	$_REQUEST['num'];
		
		vendor("Kuaidi100.kuaidi100");		
		$Kuaidi		=	new Kuaidi100();
		$content	=	$Kuaidi->query($com, $num);
		$this->ajaxReturn(1,$content,1);
	}
	
	
	
	
    
    
}




